package top.infopub.mgr.adm.web;


import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import top.infopub.mgr.adm.domain.ServeRecordAssist;
import top.infopub.mgr.adm.domain.ServeRecordDomain;
import top.infopub.mgr.adm.service.MeetingRecordService;
import top.infopub.mgr.adm.service.MeetingRoomService;
import top.infopub.mgr.adm.service.ServeRecordService;
import top.infopub.mgr.adm.vo.ServeRecordVo;
import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.ErrorCodeEnum;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.web.GenericFlowController;
import top.infopub.mgr.hr.service.StaffInfoService;
import top.infopub.mgr.util.FileHelper;
import top.infopub.mgr.util.LogUtil;
import top.infopub.mgr.util.LogUtil.AcctionType;
import top.infopub.mgr.util.LogUtil.LogModelType;
import top.infopub.model.adm.MeetingRecord;
import top.infopub.model.adm.MeetingRoom;
import top.infopub.model.adm.ServeRecord;
import top.infopub.model.adm.ServeRecordAtt;
import top.infopub.model.hr.StaffInfo;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.tdp.sys.service.CodeGeneratorConfigService;
import top.infopub.util.IdFactory;

import com.github.pagehelper.Page;


/**
 * 接待申请
 * @author Awoke
 * @version 2020年3月16日
 * @see ServeRecordController
 * @since
 */
@Controller
@RequestMapping("/serveRecord")
public class ServeRecordController extends GenericFlowController {

    @Autowired
    private CodeGeneratorConfigService codeGeneratorConfigService;

    @Autowired
    private StaffInfoService staffInfoService;

    @Autowired
    private ServeRecordService serveRecordService;

    @Autowired
    private MeetingRoomService meetingRoomService;

    @Autowired
    private MeetingRecordService meetingRecordService;

    /**
     * list页面
     * @return
     */
    @RequestMapping("/list")
    public String list() {
        return "adm/lay-serveRecord-list";
    }

    /**
     * 接待申请列表数据
     * @return
     */
    @RequestMapping("/queryDataByCondition")
    @ResponseBody
    public RspVo<ServeRecordDomain> queryDataByCondition(ServeRecordVo serveRecordVo,
                                                         ParamPage paramPage) {
        Page<ServeRecordDomain> page = new Page<ServeRecordDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (serveRecordVo.getEndDate() != null) {
            serveRecordVo.setEndDate(DateUtils.addDays(serveRecordVo.getEndDate(), 1));
        }
        page = serveRecordService.selectByDomainWhere(page, serveRecordVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 接待申请-我审批的列表数据
     *
     * @return
     */
    @RequestMapping("/queryMyCheckDataByCondition")
    @ResponseBody
    public RspVo<ServeRecordDomain> queryMyCheckDataByCondition(ServeRecordVo serveRecordVo,
                                                                ParamPage paramPage) {
        Page<ServeRecordDomain> page = new Page<ServeRecordDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (serveRecordVo.getEndDate() != null) {
            serveRecordVo.setEndDate(DateUtils.addDays(serveRecordVo.getEndDate(), 1));
        }
        serveRecordVo.setAddBy(SessionUserUtils.getSessionUserId());
        page = serveRecordService.selectMyCheckByDomainWhere(page, serveRecordVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 跳转到新增页面
     * @return
     */
    @RequestMapping("/add")
    public String toAdd(HttpServletRequest request) {
        String bindOrgId = String.valueOf(SessionUserUtils.getSessionAttribute("bindOrgId"));
        String bindOrgName = String.valueOf(SessionUserUtils.getSessionAttribute("bindOrgName"));
        String bindDeptId = String.valueOf(SessionUserUtils.getSessionAttribute("bindDeptId"));
        String bindDeptName = String.valueOf(SessionUserUtils.getSessionAttribute("bindDeptName"));
        request.setAttribute("bindOrgId", bindOrgId);
        request.setAttribute("bindOrgName", bindOrgName);
        request.setAttribute("bindDeptId", bindDeptId);
        request.setAttribute("bindDeptName", bindDeptName);
        AuthorizationVO authorizationVO = SessionUserUtils.getSessionAttributeForUserDtl();
        StaffInfo staffInfo = staffInfoService.selectByPrimaryKey(authorizationVO.getHrStaffId());
        request.setAttribute("staffName", staffInfo.getStaffName());
        //带入所有会议室
        MeetingRoom meetingRoom = new MeetingRoom();
        meetingRoom.setState(1);
        List<MeetingRoom> meetingRooms = meetingRoomService.selectByEntityWhere(meetingRoom);
        request.setAttribute("meetingRoomList", meetingRooms);
        return "adm/lay-serveRecord-add";
    }

    /**
     * 接待申请-新增
     * @throws ParseException 
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping("/save")
    @ResponseBody
    public RspVo save(ServeRecordAssist serveRecordAssist)
        throws ParseException {

        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String meetingDates = serveRecordAssist.getMeetingDates();
        String meetingStartTimes = serveRecordAssist.getMeetingStartTimes();
        String meetingEndTimes = serveRecordAssist.getMeetingEndTimes();
        String meetingStartTime = meetingDates + " " + meetingStartTimes;
        String meetingEndTime = meetingDates + " " + meetingEndTimes;
        SimpleDateFormat df1 = new SimpleDateFormat("yyyy-MM-dd");
        Date meetingDate = df1.parse(meetingDates);
        Date meetingStartTimeDate = df.parse(meetingStartTime);
        Date meetingEndTimeDate = df.parse(meetingEndTime);

        serveRecordAssist.setMeetingDate(meetingDate);
        serveRecordAssist.setMeetingStartTime(meetingStartTimeDate);
        serveRecordAssist.setMeetingEndTime(meetingEndTimeDate);

        if (StringUtils.isBlank(serveRecordAssist.getId())) {
            SimpleDateFormat df2 = new SimpleDateFormat("HH:mm:ss");
            List<ServeRecord> serveRecordList = serveRecordService.isExistTime(serveRecordAssist);
            //判断会议时间是否有重叠
            if (serveRecordList != null && serveRecordList.size() > 0) {
                StringBuilder stringBuilder = new StringBuilder();
                for (ServeRecord serveRecord : serveRecordList) {
                    //数据库中的开始时间
                    long meetingStartTimeLong = serveRecord.getMeetingStartTime().getTime();
                    //数据库中的结束时间
                    long meetingEndTimeLong = serveRecord.getMeetingEndTime().getTime();
                    //前端传的开始时间
                    long meetingStartTimeAssist = serveRecordAssist.getMeetingStartTime().getTime();
                    //前端传的结束时间
                    long meetingEndTimeAssist = serveRecordAssist.getMeetingEndTime().getTime();
                    if (meetingStartTimeAssist >= meetingStartTimeLong
                        && meetingEndTimeAssist <= meetingEndTimeLong) {
                        
                        stringBuilder.append(df2.format(serveRecordAssist.getMeetingStartTime()) + "-"
                            + df2.format(serveRecordAssist.getMeetingEndTime()) + ",");
                        
                    }else if(meetingStartTimeAssist <= meetingStartTimeLong
                        && meetingEndTimeAssist >= meetingEndTimeLong){
                        
                        stringBuilder.append(df2.format(serveRecord.getMeetingStartTime()) + "-"
                            + df2.format(serveRecord.getMeetingEndTime()) + ",");
                        
                    }else if(meetingStartTimeAssist <= meetingStartTimeLong
                        && meetingEndTimeAssist <= meetingEndTimeLong 
                        && meetingEndTimeAssist >= meetingStartTimeLong){
                        
                        stringBuilder.append(df2.format(serveRecord.getMeetingStartTime()) + "-"
                            + df2.format(serveRecordAssist.getMeetingEndTime()) + ",");
                        
                    }else if(meetingStartTimeAssist >= meetingStartTimeLong
                        && meetingEndTimeAssist >= meetingEndTimeLong 
                        && meetingStartTimeAssist <= meetingEndTimeLong 
                        && meetingEndTimeAssist >= meetingStartTimeLong){
                        
                        stringBuilder.append(df2.format(serveRecordAssist.getMeetingStartTime()) + "-"
                            + df2.format(serveRecord.getMeetingEndTime()) + ",");
                        
                    }
                }
                return ErrorCodeEnum.ERROR_COMMON_SAVE.getRspVo("接待申请-会议时间存在重叠~【重叠时间段为"
                                                                + stringBuilder.substring(0,
                                                                    stringBuilder.length() - 1));
            }
        }

        if (StringUtils.isBlank(serveRecordAssist.getId())) {
            SimpleDateFormat df2 = new SimpleDateFormat("HH:mm:ss");
            MeetingRecord meetingRecord = new MeetingRecord();
            meetingRecord.setMeetingStartTime(meetingStartTimeDate);
            meetingRecord.setMeetingEndTime(meetingEndTimeDate);
            meetingRecord.setMeetingRoomId(serveRecordAssist.getMeetingRoomId());
            List<MeetingRecord> meetingRecordList = meetingRecordService.isExistTime(meetingRecord);
            //判断会议时间是否有重叠
            if (meetingRecordList != null && meetingRecordList.size() > 0) {
                StringBuilder stringBuilder = new StringBuilder();
                for (MeetingRecord mRecord : meetingRecordList) {
                    //数据库中的开始时间
                    long meetingStartTimeLong = mRecord.getMeetingStartTime().getTime();
                    //数据库中的结束时间
                    long meetingEndTimeLong = mRecord.getMeetingEndTime().getTime();
                    //前端传的开始时间
                    long meetingStartTimeAssist = serveRecordAssist.getMeetingStartTime().getTime();
                    //前端传的结束时间
                    long meetingEndTimeAssist = serveRecordAssist.getMeetingEndTime().getTime();
                    if (meetingStartTimeAssist >= meetingStartTimeLong
                        && meetingEndTimeAssist <= meetingEndTimeLong) {
                        
                        stringBuilder.append(df2.format(serveRecordAssist.getMeetingStartTime()) + "-"
                            + df2.format(serveRecordAssist.getMeetingEndTime()) + ",");
                        
                    }else if(meetingStartTimeAssist <= meetingStartTimeLong
                        && meetingEndTimeAssist >= meetingEndTimeLong){
                        
                        stringBuilder.append(df2.format(mRecord.getMeetingStartTime()) + "-"
                            + df2.format(mRecord.getMeetingEndTime()) + ",");
                        
                    }else if(meetingStartTimeAssist <= meetingStartTimeLong
                        && meetingEndTimeAssist <= meetingEndTimeLong 
                        && meetingEndTimeAssist >= meetingStartTimeLong){
                        
                        stringBuilder.append(df2.format(mRecord.getMeetingStartTime()) + "-"
                            + df2.format(serveRecordAssist.getMeetingEndTime()) + ",");
                        
                    }else if(meetingStartTimeAssist >= meetingStartTimeLong
                        && meetingEndTimeAssist >= meetingEndTimeLong 
                        && meetingStartTimeAssist <= meetingEndTimeLong 
                        && meetingEndTimeAssist >= meetingStartTimeLong){
                        
                        stringBuilder.append(df2.format(serveRecordAssist.getMeetingStartTime()) + "-"
                            + df2.format(mRecord.getMeetingEndTime()) + ",");
                        
                    }
                }
                return ErrorCodeEnum.ERROR_COMMON_SAVE.getRspVo("会议申请-会议时间存在重叠~【重叠时间段为"
                                                                + stringBuilder.substring(0,
                                                                    stringBuilder.length() - 1));
            }
        }

        //接待申请表处理
        serveRecordAssist.setHrDeptId(serveRecordAssist.getHrDeptid());
        serveRecordAssist.setHrOrgId(serveRecordAssist.getHrOrgid());
        serveRecordAssist.setStaffName(serveRecordAssist.getStaffname());
        serveRecordAssist.setHrStaffApplyId(serveRecordAssist.getHrStaffApplyid());
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        String id = IdFactory.getUUIDUpper();
        serveRecordAssist.setId(id);
        serveRecordAssist.setAddBy(vo.getId());
        serveRecordAssist.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
        String code = codeGeneratorConfigService.generatorCode("adm_serve_record");
        serveRecordAssist.setCodes(code);
        // 处理processId
        serveRecordAssist.setProcessId(IdFactory.getUUIDUpper());
        serveRecordAssist.setProcessStatus("1");//审批中
        serveRecordAssist.setUptBy(vo.getId());
        serveRecordAssist.setUptTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());

        //上传附件
        List<ServeRecordAtt> serveRecordAtts = new ArrayList<ServeRecordAtt>();
        //接待方案(选填)
        String[] fileAtts1 = serveRecordAssist.getFileAtts1();
        if (fileAtts1 != null) {
            for (String file : fileAtts1) {
                ServeRecordAtt serveRecordAtt = createFileAtt(vo, id, file);
                serveRecordAtt.setTypes("1");
                serveRecordAtts.add(serveRecordAtt);
            }
        }
        //其他附件(选填)
        String[] fileAtts2 = serveRecordAssist.getFileAtts2();
        if (fileAtts2 != null) {
            for (String file : fileAtts2) {
                ServeRecordAtt serveRecordAtt = createFileAtt(vo, id, file);
                serveRecordAtt.setTypes("2");
                serveRecordAtts.add(serveRecordAtt);
            }
        }
        serveRecordService.saveServeRecord(serveRecordAssist, serveRecordAtts);
        LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD, null, null);
        return RspVo.getSuccessResponse();
    }

    private ServeRecordAtt createFileAtt(AuthorizationVO vo, String recordId, String file) {
        //资料信息数组
        String[] fileAttStr = file.split("\\|");
        ServeRecordAtt fileAtt = new ServeRecordAtt();
        fileAtt.setId(fileAttStr[2]);
        fileAtt.setRecordId(recordId);//接待申请id
        String fileName = fileAttStr[1].substring(0, fileAttStr[1].lastIndexOf("."));
        String suffix = fileAttStr[1].substring(fileAttStr[1].lastIndexOf("."),
            fileAttStr[1].length()).toLowerCase();//后缀转小写
        fileAtt.setFileName(fileName);//文件名
        fileAtt.setFileSuffix(suffix);//文件后缀
        fileAtt.setFilePath(fileAttStr[3]);//文件保存路径
        fileAtt.setAddBy(vo.getId());//添加人
        fileAtt.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());//添加时间
        return fileAtt;
    }

    /**
     * 上传附件
     * @param request
     * @param response
     * @return 
     * @throws IOException 
     * @see
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping("/uploadAtt")
    public @ResponseBody RspVo uploadAtt(HttpServletRequest request)
        throws IOException {
        List<String> returnFileStrList = new ArrayList<>();
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest)request;
        Map<String, MultipartFile> map = multipartHttpServletRequest.getFileMap();
        if (map != null) {
            for (String name : map.keySet()) {
                MultipartFile file = map.get(name);
                //资料类型
                String types = request.getParameter("types");
                if (StringUtils.isEmpty(types)) {
                    return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("缺少参数");
                }
                // 上传文件
                String fileId = IdFactory.getUUIDSerialNumber();
                // 服务器资源路径
                String serverPath = "serveRecord";
                String filePath = FileHelper.upload(file, serverPath);
                returnFileStrList.add(types + "|" + file.getOriginalFilename().trim() + "|"
                                      + fileId + "|" + filePath);
                LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD, "上传接待申请附件-文件名:" + filePath
                                                                      + "，文件路径:" + filePath, null);
            }
        }
        return RspVo.getSuccessResponse(returnFileStrList);
    }

    /**
     * 根据id查询设备合同详细  > 注意：方法命名必须为：toDealOrDetail
     * @param id 接待申请id
     * @return
     * @see
     */
    @RequestMapping("/toDealOrDetail")
    public ModelAndView queryById(HttpServletRequest request, String id, String processDealWith) {
        Map<String, Object> map = new HashMap<String, Object>();
        ServeRecordVo serveRecordVo = serveRecordService.queryById(id);
        request.setAttribute("modelDetail", serveRecordVo);
        map.put("serveRecordVo", serveRecordVo);
        // 审批flag
        request.setAttribute("processDealWith", processDealWith);
        // 审批data
        processData(request, serveRecordVo.getProcessId());
        return new ModelAndView("adm/lay-serveRecord-detail", map);
    }

}
